package com.hljx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hljx.bo.vo.SysDictVO;
import com.hljx.config.exception.DataException;
import com.hljx.dto.SysDictDTO;
import com.hljx.dto.SysDictPageDTO;
import com.hljx.entity.SysDict;
import com.hljx.entity.SysDictItem;
import com.hljx.mapper.SysDictMapper;
import com.hljx.service.SysDictItemService;
import com.hljx.service.SysDictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 字典 服务实现类
 * </p>
 *
 * @author gx
 * @since 2023-09-18
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {

    @Autowired
    SysDictItemService dictItemService;

    @Override
    public Boolean saveOrUpdateDict(SysDictDTO dto) {
        long count = baseMapper.selectCount(new LambdaQueryWrapper<SysDict>().eq(SysDict::getCode, dto.getCode())
                .ne(dto.getId() != null, SysDict::getId, dto.getId()));
        if(count>0){
            throw new DataException("字典编码重复",201);
        }
        long result = baseMapper.selectCount(new LambdaQueryWrapper<SysDict>().eq(SysDict::getName,dto.getName()).eq(StringUtils.isNotBlank(dto.getSource()),SysDict::getSource,dto.getSource())
                .ne(dto.getId() != null, SysDict::getId, dto.getId()));
        if(result>0){
            throw new DataException("字典名称重复",201);
        }
        SysDict sysDict = new SysDict();
        BeanUtil.copyProperties(dto,sysDict);
        return saveOrUpdate(sysDict);
    }

    @Override
    public Boolean deleteDict(Long id) {
        long count = dictItemService.count(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getDictId, id));
        if(count>0){
            throw new DataException("请先删除该数据下的字典数据项",201);
        }
        return removeById(id);
    }

    @Override
    public IPage<SysDictVO> listSysDictByPage(SysDictPageDTO dto) {
        Page<SysDictVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        return baseMapper.listSysDictByPage(page, dto);
    }
}
